using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SimpleFramework
{
    public class TimerSystem : TMonoSingletonX<TimerSystem>
    {
        private List<ITimer> m_AddQueue = new List<ITimer>();
        private List<ITimer> m_RunQueue = new List<ITimer>();

        // Update is called once per frame
        void Update()
        {
            if (Timer.IsPause)
            {
                return;
            }

            if (m_AddQueue.Count > 0)
            {
                for (int j = 0; j < m_AddQueue.Count; ++j)
                {
                    var updater = m_AddQueue[j];
                    if (!m_RunQueue.Contains(updater))
                    {
                        m_RunQueue.Add(updater);
                    }
                }
                m_AddQueue.Clear();
            }

            int i = 0;
            while (i < m_RunQueue.Count)
            {
                if (m_RunQueue[i].Update())
                {
                    m_RunQueue.RemoveAt(i);
                }
                else
                {
                    ++i;
                }
            }
        }

        public void Add(ITimer updater)
        {
            m_AddQueue.Add(updater);
        }

        public void Remove(ITimer updater)
        {
            m_RunQueue.Remove(updater);
            m_AddQueue.Remove(updater);
        }
    }
}